package cn.doctor.assistant.pad.ui;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.easemob.EMCallBack;
import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMMessage;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.doctor.assistant.pad.MyApplication;
import cn.doctor.assistant.pad.R;
import cn.doctor.assistant.pad.base.BaseNetActivity;
import cn.doctor.assistant.pad.entity.AssUser;
import cn.doctor.assistant.pad.ui.hudong.IMFragment;
import cn.doctor.assistant.pad.ui.huifang.RecallFragment;
import cn.doctor.assistant.pad.ui.tongji.StatisticsFragment;
import cn.doctor.assistant.pad.ui.zhuanzhen.TransferFragment;
import cn.doctor.assistant.pad.ui.zhuye.HomeFragment;
import cn.doctor.assistant.pad.ui.ziliao.InformationFragment;
import cn.doctor.assistant.pad.view.PopMenu;

public class MainActivity extends BaseNetActivity implements EMEventListener {

    @InjectView(R.id.main_navigate_list)
    ListView mainNavigateList;

    NavigationAdapter mNavAdapter;

    @InjectView(R.id.main_doctor_icon)
    ImageView mainDoctorIcon;
    @InjectView(R.id.main_doctor_name)
    TextView mainDoctorName;

    PopMenu popMenu;
    ListView mPopList;

    // 主页左侧导航菜单项
    List<MainItem> items = new ArrayList<>(
            Arrays.asList(
                    new MainItem(R.drawable.ic_home_white_24dp, "主页", MainItem.MAIN_ITEM_TAG_HOME),
                    new MainItem(R.drawable.ic_assignment_white_24dp, "资料", MainItem.MAIN_ITEM_TAG_INFO),
                    new MainItem(R.drawable.ic_call_white_24dp, "回访", MainItem.MAIN_ITEM_TAG_RECALL),
                    new MainItem(R.drawable.ic_swap_horiz_white_24dp, "转诊",MainItem.MAIN_ITEM_TAG_TRANSFER),
                    new MainItem(R.drawable.ic_chat_white_24dp, "互动",MainItem.MAIN_ITEM_TAG_IM),
                    new MainItem(R.drawable.ic_insert_chart_white_24dp, "统计", MainItem.MAIN_ITEM_TAG_STATISTICS)
            )
    );

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);

        initLeftNavigation();

        if (savedInstanceState == null) {
            int position = 0;
            selectItem(position, items.get(position).getTag());
        }

        // XXX 环信登录
        //loginIM();
    }

    private void initLeftNavigation() {
        // 初始化“我的医生”，医生可能有多个，需要从文件中读取上次的医生信息
        updateCurrentDoctor();

        // 导航菜单列表
        mNavAdapter = new NavigationAdapter(this, R.layout.main_item, items);
        mainNavigateList.setAdapter(mNavAdapter);
        mainNavigateList.setOnItemClickListener(new MainItemClickListener());

        // 我的医生列表
        mPopList = (ListView) LayoutInflater.from(this).inflate(R.layout.layout_listview, null);
        popMenu = new PopMenu(mainDoctorIcon, mPopList);
        mPopList.setAdapter(new PopListAdapter());

        mPopList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                showToast("click..."+position);
                // 切换当前医生
                MyApplication.getInstance().switchCurrentDoctor(position);
                // 更新UI
                updateCurrentDoctor();
            }
        });

        mainDoctorIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popMenu.show();
            }
        });
    }

    void updateCurrentDoctor() {
        AssUser currentDoctor = MyApplication.getInstance().mCurrDoctor;
        if (!TextUtils.isEmpty(currentDoctor.getThumb())) {
            Picasso.with(this).load(currentDoctor.getThumb()).into(mainDoctorIcon);
        }
        mainDoctorName.setText(currentDoctor.getReal_name());
    }

    private class PopListAdapter extends BaseAdapter{

        List<AssUser> doctors;
        public PopListAdapter() {
            doctors = MyApplication.getInstance().mDoctors;
        }

        @Override
        public int getCount() {
            return doctors.size();
        }

        @Override
        public Object getItem(int position) {
            return doctors.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;

            if (convertView == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(MainActivity.this).inflate(R.layout.list_item_home_popup, parent, false);
                holder.icon = (ImageView) convertView.findViewById(R.id.popup_doctor_icon);
                holder.name = (TextView) convertView.findViewById(R.id.popup_doctor_name);
                convertView.setTag(holder);
            }else {
                holder = (ViewHolder) convertView.getTag();
            }

            AssUser doctor = doctors.get(position);
            if (!TextUtils.isEmpty(doctor.getThumb())) {
                Picasso.with(MainActivity.this).load(doctor.getThumb()).into(holder.icon);
            }
            holder.name.setText(doctor.getReal_name());
            return convertView;
        }

        class ViewHolder{
            ImageView icon;
            TextView name;
        }
    }

    private class MainItemClickListener implements
            ListView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position, items.get(position).getTag());
        }
    }

    private void selectItem(int position, String tag) {
        setCurrentFragmentByTag(tag);

        mainNavigateList.setItemChecked(position, true);
    }

    private String mLastFragmentTag;

    private void setCurrentFragmentByTag(String tag) {
        FragmentManager fm = getSupportFragmentManager();

        Fragment fragment = fm.findFragmentByTag(tag);

        if (fragment == null) {
            switch (tag) {
                case MainItem.MAIN_ITEM_TAG_HOME:
                    fragment = HomeFragment.newInstance();
                    break;
                case MainItem.MAIN_ITEM_TAG_INFO:
                    fragment = InformationFragment.newInstance();
                    break;
                case MainItem.MAIN_ITEM_TAG_RECALL:
                    fragment = RecallFragment.newInstance();
                    break;
                case MainItem.MAIN_ITEM_TAG_IM:
                    fragment = IMFragment.newInstance();
                    break;
                case MainItem.MAIN_ITEM_TAG_TRANSFER:
                    fragment = TransferFragment.newInstance();
                    break;
                case MainItem.MAIN_ITEM_TAG_STATISTICS:
                    fragment = StatisticsFragment.newInstance();
                    break;
            }

            fm.beginTransaction().add(R.id.content_frame, fragment, tag).commit();

        } else {
            fm.beginTransaction().show(fragment).commit();
        }

        if (mLastFragmentTag != null && !mLastFragmentTag.equals(tag)) {
            Fragment oldFragment = fm.findFragmentByTag(mLastFragmentTag);
            if (oldFragment != null) {
                fm.beginTransaction().hide(oldFragment).commit();
            }
        }

        mLastFragmentTag = tag;
    }

    private void loginIM() {
        String assisName = "15855667788";
        String pwd = "superDoctor"; // XXX :注意环信的密码统一是superDoctor
        EMChatManager.getInstance().login(assisName, pwd, new EMCallBack() {
            @Override
            public void onSuccess() {
                UI.showToast("登录环信成功");
            }

            @Override
            public void onError(int i, String s) {
                Log.e("jzsn", "环信登录失败：" + s);
            }

            @Override
            public void onProgress(int i, String s) {
            }
        });

        EMChatManager.getInstance().registerEventListener(this);
        EMChat.getInstance().setAppInited();
    }

    @Override
    public void onEvent(EMNotifierEvent event) {
        EMMessage message = null;
        if (event.getData() instanceof EMMessage) {
            message = (EMMessage) event.getData();
            Log.d("jlf", "SimpleChat: receive the event : " + event.getEvent() + ",id : " + message.getMsgId());
            UI.showToast(message.getBody().toString());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EMChatManager.getInstance().logout();
    }
}

